from api.views import error, render
from . import juhe 
from django.views.decorators.http import require_http_methods
from .models import Cache, PreparedProduct
import json, urllib2, socket
from django.db.models import Q

# Create your views here.
@require_http_methods(["GET"])
def product_list(request):
    keyword =  request.GET.get('keyword')
    
    products = PreparedProduct.objects.filter(Q(spname__contains=keyword) | Q(sid=keyword) | Q(mid=keyword) )[0:10]
    
    if products.count() == 0:
        try:
            cache = Cache.objects.get(keyword=keyword)
            products = json.loads(cache.content, "utf-8")
        except Cache.DoesNotExist:
            try:
                products = juhe.search(keyword=keyword)
                cache = Cache(**{"keyword": keyword,"content": json.dumps(products) })
                cache.save()
                products = json.loads(cache.content, "utf-8")
                #for p in products:
                #    p['image_src'] = "http://proc.justpay.com.cn/i/vurl/%s/30x30@2x" % p['image_src']
            except (urllib2.HTTPError, socket.timeout) as e:
                products = [] 
            
    return render({"products": products})

@require_http_methods(["GET"])
def product_list2(request):
    keyword =  request.GET.get('keyword')
    
    try:
        cache = Cache.objects.get(keyword=keyword)
        products = json.loads(cache.content, "utf-8")
    except Cache.DoesNotExist:
        try:
            products = juhe.search(keyword=keyword)
            cache = Cache(**{"keyword": keyword,"content": json.dumps(products) })
            cache.save()
            products = json.loads(cache.content, "utf-8")
        except (urllib2.HTTPError, socket.timeout) as e:
            products = [] 
            
    return render({"products": products})
